package com.campus.lostandfound.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.lostandfound.entity.ItemInfo;
import com.campus.lostandfound.mapper.ItemInfoMapper;
import com.campus.lostandfound.service.ItemInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 失物/招领信息Service实现类
 */
@Service
public class ItemInfoServiceImpl extends ServiceImpl<ItemInfoMapper, ItemInfo> implements ItemInfoService {
    
    @Override
    public boolean publishInfo(ItemInfo itemInfo) {
        // 生成信息编号
        String prefix = itemInfo.getType() == 0 ? "SW" : "ZL";
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        
        // 获取当月流水号
        LambdaQueryWrapper<ItemInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(ItemInfo::getInfoNo, prefix + dateStr);
        long count = count(wrapper);
        
        String infoNo = String.format("%s%s%04d", prefix, dateStr, count + 1);
        itemInfo.setInfoNo(infoNo);
        
        // 设置默认状态
        itemInfo.setStatus(0); // 待审核
        
        return save(itemInfo);
    }
    
    @Override
    @CacheEvict(value = "itemPage", allEntries = true)
    public boolean auditInfo(Long id, Integer status, String auditComment) {
        ItemInfo itemInfo = getById(id);
        if (itemInfo == null) {
            throw new RuntimeException("信息不存在");
        }
        
        if (itemInfo.getStatus() != 0) {
            throw new RuntimeException("该信息已审核");
        }
        
        itemInfo.setStatus(status);
        itemInfo.setAuditComment(auditComment);
        itemInfo.setAuditTime(LocalDateTime.now());
        
        // 如果审核通过，设置失效时间（90天后）
        if (status == 1) {
            itemInfo.setExpireTime(LocalDateTime.now().plusDays(90));
        }
        
        System.out.println("【缓存】清除物品列表缓存");
        return updateById(itemInfo);
    }
    
    @Override
    public IPage<ItemInfo> pageQuery(Integer current, Integer size, Map<String, Object> params) {
        Page<ItemInfo> page = new Page<>(current, size);
        LambdaQueryWrapper<ItemInfo> wrapper = new LambdaQueryWrapper<>();
        
        // 只查询已发布的信息
        wrapper.eq(ItemInfo::getStatus, 1);
        
        // 关键词搜索
        String keyword = (String) params.get("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.and(w -> w.like(ItemInfo::getItemName, keyword)
                             .or()
                             .like(ItemInfo::getDescription, keyword));
        }
        
        // 类型筛选
        Object typeObj = params.get("type");
        if (typeObj != null) {
            Integer type = typeObj instanceof Number ? ((Number) typeObj).intValue() : null;
            if (type != null) {
                wrapper.eq(ItemInfo::getType, type);
            }
        }
        
        // 物品类别筛选
        Object categoryObj = params.get("category");
        if (categoryObj != null) {
            Integer category = categoryObj instanceof Number ? ((Number) categoryObj).intValue() : null;
            if (category != null) {
                wrapper.eq(ItemInfo::getCategory, category);
            }
        }
        
        // 地点筛选
        String locationArea = (String) params.get("locationArea");
        if (StringUtils.isNotBlank(locationArea)) {
            wrapper.eq(ItemInfo::getLocationArea, locationArea);
        }
        
        // 时间范围筛选
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isNotBlank(startDate)) {
            wrapper.ge(ItemInfo::getLostDate, LocalDate.parse(startDate));
        }
        if (StringUtils.isNotBlank(endDate)) {
            wrapper.le(ItemInfo::getLostDate, LocalDate.parse(endDate));
        }
        
        // 按发布时间倒序
        wrapper.orderByDesc(ItemInfo::getCreateTime);
        
        return page(page, wrapper);
    }
    
    @Override
    public IPage<ItemInfo> getMyPublish(String userId, Integer current, Integer size) {
        Page<ItemInfo> page = new Page<>(current, size);
        LambdaQueryWrapper<ItemInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ItemInfo::getPublisherId, userId);
        wrapper.orderByDesc(ItemInfo::getCreateTime);
        
        return page(page, wrapper);
    }
    
    @Override
    public boolean deleteInfo(Long id, String userId) {
        ItemInfo itemInfo = getById(id);
        if (itemInfo == null) {
            throw new RuntimeException("信息不存在");
        }
        
        if (!itemInfo.getPublisherId().equals(userId)) {
            throw new RuntimeException("无权删除该信息");
        }
        
        // 只有待审核、审核驳回、已失效状态可以删除
        if (itemInfo.getStatus() != 0 && itemInfo.getStatus() != 3 && itemInfo.getStatus() != 4) {
            throw new RuntimeException("当前状态不允许删除");
        }
        
        return removeById(id);
    }
}

